<template>
  <div class="navbar">
    <div class="left-side">
      <el-space>
        <img alt="logo" :width="26" src="@/assets/logo.png"/>
        <el-text :style="{ margin: 0, fontWeight: 'bold' }" size="large">GinMeta-Admin</el-text>
        <el-icon v-if="appStore.device === 'mobile'" style="font-size: 22px; cursor: pointer"
                 @click="toggleDrawerMenu">
          <Menu/>
        </el-icon>
      </el-space>
    </div>
    <ul class="right-side">
      <!--      <li>
              <el-tooltip :content="theme === 'light' ? '黑暗模式' : '明亮模式'">
                <el-button class="nav-btn" type="text" :shape="'circle'" @click="handleToggleTheme">
                  <template #icon>
                    <el-icon v-if="theme !== 'dark'">
                      <Moon/>
                    </el-icon>
                    <el-icon v-else>
                      <Sunny/>
                    </el-icon>
                  </template>
                </el-button>
              </el-tooltip>
            </li>-->
      <li>
        <el-dropdown trigger="click">
          <el-avatar :size="32" :style="{ marginRight: '8px', cursor: 'pointer' }">
            <img v-if="avatar !== ''" alt="avatar" :src="avatar"/>
            <span v-else>A</span>
          </el-avatar>
          <template #dropdown>
            <el-dropdown-item>
              <el-space @click="handleUserInfo">
                <el-icon>
                  <User/>
                </el-icon>
                <span>个人中心</span>
              </el-space>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-space @click="handleEditPassword">
                <el-icon>
                  <Edit/>
                </el-icon>
                <span>修改密码</span>
              </el-space>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-space @click="handleLogout">
                <el-icon>
                  <Close/>
                </el-icon>
                <span>退出登陆</span>
              </el-space>
            </el-dropdown-item>
          </template>
        </el-dropdown>
      </li>
    </ul>

    <el-dialog v-model="formModelSetting.visible"
               :title="formModelSetting.title"
               @close="handleCancel">

      <el-form ref="formRef" :model="userInfo" label-width="auto" label-position="right">
        <el-form-item prop="avatar" label="头像">
          <el-upload
              ref="upload"
              class="avatar-uploader"
              :show-file-list="false"
              :http-request="customUpload"
              :on-exceed="exceedUpload"
              :limit="1"
          >
            <img v-if="avatar" :src="avatar" class="avatar" width="60" height="60"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="用户名" :rules="[{required:true,message:'用户名不能为空'}]">
          <el-input v-model="userInfo.username" readonly/>
        </el-form-item>
        <el-form-item prop="nickName" label="昵称" :rules="[{required:true,message:'昵称不能为空'}]">
          <el-input v-model="userInfo.nickName" placeholder="请输入昵称" max-length="10" show-word-limit/>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio-group v-model="userInfo.gender">
            <el-radio value="M">男</el-radio>
            <el-radio value="F">女</el-radio>
            <el-radio value="N" disabled>隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="userInfo.phone" placeholder="请输入手机号" max-length="11" show-word-limit/>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="userInfo.email" placeholder="请输入邮箱" max-length="16" show-word-limit/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleOk">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog ref="modalRefPwd"
               v-model="modelSettingPwd.visible"
               :title="modelSettingPwd.title"
               @cancel="handleCancelPwd">
      <el-form ref="formDataRefPwd" :model="formDataPwd" label-width="auto" label-position="right">
        <el-form-item prop="oldPassword" label="旧密码"
                      :rules="[{required:true, message:'旧密码不能为空', type: 'string'}]">
          <el-input v-model="formDataPwd.oldPassword" type="password" placeholder="请输入旧密码" max-length="16"
                    show-word-limit/>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码"
                      :rules="[{required:true, message:'新密码不能为空', type: 'string'}]">
          <el-input v-model="formDataPwd.newPassword" type="password" placeholder="请输入新密码" max-length="16"
                    show-word-limit/>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码"
                      :rules="[{required:true, message:'确认密码不能为空', type: 'string'}]">
          <el-input v-model="formDataPwd.confirmPassword" type="password" placeholder="请再次输入新密码" max-length="16"
                    show-word-limit/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button @click="handleCancelPwd">取消</el-button>
          <el-button type="primary" @click="handleOkPwd">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, inject, reactive, ref} from 'vue';
import type {UploadRawFile} from 'element-plus'
import {ElMessage, genFileId} from 'element-plus'
import {useDark, useToggle} from '@vueuse/core';
import {useAppStore, useUserStore} from '@/store';
import useUser from '@/hooks/user';
import {editInfo, editPwd, EditPwdParams, editUserInfoParams, uploadAvatar} from '@/api/system/user';
import {useRouter} from 'vue-router';

const baseUrl = import.meta.env.VITE_API_BASE_URL;
const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();
const {logout} = useUser();
const file = ref();
const formRef = ref();
const avatar = computed(() => {
  if (userStore.avatar === '') {
    return userStore.avatar;
  }
  return baseUrl + userStore.avatar;
});
const userInfo = reactive({
  userId: userStore.userId,
  avatar: userStore.avatar,
  username: userStore.username,
  nickName: userStore.nickName,
  phone: userStore.phone,
  email: userStore.email,
  gender: userStore.gender,
});
const fileInfo = reactive({
  uid: '',
  name: '',
  url: '',
});
// 退出登陆
const handleLogout = () => {
  logout();
};
// 折叠菜单按钮
const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
const theme = computed(() => {
  return appStore.theme;
});
const isDark = useDark({
  selector: 'body',
  attribute: 'arco-theme',
  valueDark: 'dark',
  valueLight: 'light',
  storageKey: 'arco-theme',
  onChanged(dark: boolean) {
    // overridden default behavior
    appStore.toggleTheme(dark);
  },
});
const toggleTheme = useToggle(isDark);
const handleToggleTheme = () => {
  toggleTheme();
};

// 对话框是否展示
const formModelSetting = reactive({
  visible: false,
  onLoading: false,
  title: "个人信息",
  okTest: "修改",
});
// 个人信息按钮
const handleUserInfo = () => {
  // 打开弹窗
  formModelSetting.visible = true;
  // 回显头像
  if (userStore.avatar !== '') {
    fileInfo.url = baseUrl + userStore.avatar;
    file.value = fileInfo;
  }
};
// 表单确定创建之前执行
const modelBeforeOkBut = async () => {
  let flag = true;
  // 提交表单
  await formRef.value.validate().then((res: any) => {
    if (res !== undefined) {
      flag = false;
      formModelSetting.visible = true;
      formModelSetting.onLoading = false;
    }
  });
  return flag;
};
// 弹窗确认按钮
const handleOk = async () => {
  const params: editUserInfoParams = userInfo;
  const res = await editInfo(params);
  // @ts-ignore
  if (res.code === 200) {
    ElMessage.success({
      message: '修改成功',
      duration: 2 * 1000,
    });
    // 关闭弹窗
    formModelSetting.visible = false;
    // 重置头像
    fileInfo.url = '';
  } else {
    // 不关闭弹窗
    formModelSetting.visible = true;
  }
};
// 弹窗取消按钮
const handleCancel = () => {
  // 关闭弹窗
  formModelSetting.visible = false;
  // 重置头像
  fileInfo.url = '';
};
const upload = ref()
// 头像自定义上传
const customUpload = async (option: any) => {
  const formData = new FormData();
  formData.append("avatarFile", option.file);
  const res = await uploadAvatar(formData);
  // @ts-ignore
  if (res.code === 200 && res.data) {
    // 更新头像缓存
    userStore.avatar = res.data;
  }
};
const exceedUpload = async (files: File[]) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile;
  file.uid = genFileId()
  const formData = new FormData();
  formData.append("avatarFile", file);
  const res = await uploadAvatar(formData);
  // @ts-ignore
  if (res.code === 200 && res.data) {
    // 更新头像缓存
    userStore.avatar = res.data;
  }
}

/* 修改密码 - start */
const modalRefPwd = ref();
const formDataRefPwd = ref();

// 表单
const formDataPwd = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 重置表单
const resetFormDataPwd = async () => {
  formDataPwd.oldPassword = '';
  formDataPwd.newPassword = '';
  formDataPwd.confirmPassword = '';
  if (formDataRefPwd.value) {
    formDataRefPwd.value.clearValidate();
  }
}

// 对话框
const modelSettingPwd = reactive({
  visible: false,
  onLoading: false,
  title: '',
  okText: '',
  cancelText: ''
})

// 修改密码按钮
const handleEditPassword = async () => {
  // 重置表单
  await resetFormDataPwd();
  // 打开对话框
  modelSettingPwd.title = '修改密码';
  modelSettingPwd.visible = true;
}

// 取消对话框按钮
const handleCancelPwd = () => {
  // 重置表单
  resetFormDataPwd();
  // 关闭对话框
  modelSettingPwd.title = '';
  modelSettingPwd.visible = false;
  modelSettingPwd.onLoading = false;
}

// 确定对话框之前
const handleBeforeOkPwd = async () => {
  let flag = true;
  // 提交表单
  await formDataRefPwd.value.validate().then((res: any) => {
    if (res !== undefined) {
      flag = false;
    }
  });
  if (formDataPwd.newPassword !== formDataPwd.confirmPassword) {
    ElMessage.warning({
      message: '两次密码输入不一致',
      duration: 2 * 1000
    });
    formDataRefPwd.value.setFields({
      newPassword: {
        status: 'error',
        message: '两次密码输入不一致'
      },
      confirmPassword: {
        status: 'error',
        message: '两次密码输入不一致'
      }
    });
    flag = false;
  }
  return flag;
}

// 确定对话框按钮
const handleOkPwd = async () => {
  const flag = await handleBeforeOkPwd();

  if (flag) {
    const params: EditPwdParams = {
      oldPassword: formDataPwd.oldPassword,
      newPassword: formDataPwd.newPassword,
    }
    const {code}: any = await editPwd(params);
    if (code === 200) {
      ElMessage.success({
        message: '修改密码成功，请重新登录！',
        duration: 2 * 1000
      });
      await userStore.logout();
      const currentRoute = router.currentRoute.value;
      await router.push({
        name: 'login',
        query: {
          ...router.currentRoute.value.query,
          redirect: currentRoute.name as string,
        },
      });
    }
    // 重置表单
    await resetFormDataPwd();
    // 关闭对话框
    modelSettingPwd.title = '';
    modelSettingPwd.visible = false;
    modelSettingPwd.onLoading = false;
  }
}
/* 修改密码 - end */


</script>

<style scoped lang="less">
.navbar {
  display: flex;
  justify-content: space-between;
  height: 100%;
  background-color: #fff;
  border-bottom: 1px solid #f2f3f5;
}

.left-side {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.right-side {
  display: flex;
  padding-right: 20px;
  list-style: none;

  :deep(.locale-select) {
    border-radius: 20px;
  }

  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  a {
    color: var(--color-text-1);
    text-decoration: none;
  }

  .nav-btn {
    border-color: rgb(var(--gray-2));
    color: rgb(var(--gray-8));
    font-size: 16px;
  }

  .trigger-btn,
  .ref-btn {
    position: absolute;
    bottom: 14px;
  }

  .trigger-btn {
    margin-left: 14px;
  }
}
</style>

<style lang="less">
.message-popover {
  .arco-popover-content {
    margin-top: 0;
  }
}

.modal-avatar {
  text-align: center;
  margin-bottom: 20px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
